import React, { useState, useEffect } from 'react';
import { addCdnConfig, updateCdnConfig, deleteCdnConfig, queryAllCdnConfigs, deployCdn, offlineCdn, clearCache } from '../../api/cdnConfigApi';
import { CdnNode } from '../../types/CdnNode';
import { getNodes } from '../../api/cdnNodeApi';
import { CdnConfig } from '../../types/CdnConfig';
import ARecordAPI from '../../api/CNameApi';
import { ARecord } from '../../types/CdnARecord';



const CdnConfigPage = () => {
  const [domain, setDomain] = useState('');
  const [originIp, setOriginIp] = useState('');
  const [currentRecordId, setCurrentRecordId] = useState<number | null>(null);
  const [records, setRecords] = useState<CdnConfig[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [deployingId, setDeployingId] = useState<number | null>(null);
  const [offlineingId, setOfflineingId] = useState<number | null>(null);
  const [clearCacheId, setClearCacheId] = useState<number | null>(null);
  const [showCertModal, setShowCertModal] = useState(false);
  const [selectedCert, setSelectedCert] = useState<{ fullchain: string; privkey: string }>({ fullchain: '', privkey: '' });
  const [nodes, setNodes] = useState<CdnNode[]>([]);
  const [cnames, setCnames] = useState<ARecord[]>([]);
  const [selectedNodes, setSelectedNodes] = useState<number[]>([]); // 新增：选中的节点ID数组
  const [selectedCNAME, setSeleectCNAME] = useState<number>(); // 
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  const showToast = (message: string, type: "success" | "error" = "success") => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000); // 3秒后自动消失
  };

  const fetchNodes = async () => {
    try {
      const res = await getNodes();
      setNodes(res);
    } catch (error) {
      console.error(error);
    }
  };

  const fetchCNAMEs = async () => {
    try {
      const res = await ARecordAPI.getAll();
      setCnames(res.data);
    } catch (error) {
      console.error(error);
    }
  };

  // 获取数据并增加 deployStatus
  const fetchRecords = async () => {
    try {
      const fetchedRecords = await queryAllCdnConfigs();
      const dataWithStatus = fetchedRecords.map((item: CdnConfig) => (
        console.log(item),
        {
          ...item,
          deployStatus: item.ifDeploy ? '已部署' : '未部署',
        }));
      setRecords(dataWithStatus);
    } catch (error) {
      console.error('Error fetching CDN configurations:', error);
    }
  };

  useEffect(() => {
    fetchRecords();
    fetchNodes();
    fetchCNAMEs();
  }, []);

  const handleAddRecord = async () => {
    const payload = {
      userId: 1,
      domain,
      originIp,
      nodeIds: selectedNodes, // 新增：选择的节点 ID 数组
      cnameId: selectedCNAME  //选择came
    };

    if (currentRecordId !== null) {
      await updateCdnConfig(currentRecordId, payload);
      setCurrentRecordId(null);
    } else {
      await addCdnConfig(payload);
    }

    // 重置表单
    setDomain('');
    setOriginIp('');
    setSelectedNodes([]); // 清空选择的节点
    setShowModal(false);
    fetchRecords(); // 刷新列表
  };

  const handleDeleteRecord = async (id: number) => {
    if (window.confirm("确定要删除这条记录吗？")) {
      await deleteCdnConfig(id);
      fetchRecords();
    }
  };

  const handleDeploy = async (id: number) => {
    setDeployingId(id); // 显示部署中模态框
    try {
      const response = await deployCdn(id); // 假设 deployCdn 返回完整的响应

      // 检查响应状态
      if (response.status === "failed") {
        // 显示后端返回的详细错误信息
        setErrorMsg(
          `🚨 部署失败 🚨\n\n错误信息: ${response.message}` +
          (response.details ? `\n详细信息: ${response.details}` : "")
        );
      } else {
        fetchRecords(); // 刷新状态
      }
    } catch (err: any) {
      showToast(err.response?.data?.detail || "部署失败", "error");
    } finally {
      setDeployingId(null); // 关闭模态框
    }
  };

  /** ✅ 下线 */
  const handleOffline = async (id: number) => {
    setOfflineingId(id);
    try {
      const response = await offlineCdn(id);

      if (response.status === "failed") {
        alert(`下线失败: ${response.message}\n${response.details || ""}`);
      } else {
        fetchRecords();
      }
    } catch (error) {
      const err = error as { response?: { data?: { message?: string } } };
      console.error('下线失败:', err);
      if (err.response?.data?.message) {
        alert(`下线失败: ${err.response.data.message}`);
      } else {
        alert('下线失败，请重试');
      }
    } finally {
      setOfflineingId(null);
    }
  };
  // 清除缓存
  const handleClearCache = async (id: number) => {
    setClearCacheId(id);
    try {
      const response = await clearCache(id);

      if (response.status === "failed") {
        alert(`缓存删除失败: ${response.message}\n${response.details || ""}`);
      } else {
        fetchRecords();
      }
    } catch (error) {
      const err = error as { response?: { data?: { message?: string } } };
      console.error('缓存删除失败:', err);
      if (err.response?.data?.message) {
        alert(`缓存删除失败: ${err.response.data.message}`);
      } else {
        alert('缓存删除失败，请重试');
      }
    } finally {
      setClearCacheId(null);
    }
  };

  const handleEditRecord = (id: number) => {
    const record = records.find(record => record.id === id);
    if (record) {
      setDomain(record.domain);
      setOriginIp(record.originIp);
      setCurrentRecordId(id);

      // 设置已选节点
      if (record.nodes) {
        const nodeIds = record.nodes.map((node: { id: number }) => node.id);
        setSelectedNodes(nodeIds);
      } else {
        setSelectedNodes([]);
      }
    }
    setShowModal(true);
  };


  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleAddRecord();
  };

  const handleShowCert = (record: CdnConfig) => {
    if (record.fullchain && record.privkey) {
      setSelectedCert({ fullchain: record.fullchain, privkey: record.privkey });
      setShowCertModal(true);
    } else {
      alert('该 CDN 配置尚未部署证书或证书不存在');
    }
  };
  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text).then(() => alert('已复制到剪贴板'));
  };


  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* 消息弹窗 */}
      {toast && (
        <div
          className={`fixed top-5 right-5 z-50 px-4 py-2 rounded shadow-lg text-white ${toast.type === "success" ? "bg-green-500" : "bg-red-500"
            }`}
        >
          {toast.message}
        </div>
      )}

      {/* 标题区 */}
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">CDN 配置管理</h1>
        <button
          className="bg-blue-600 text-white py-2 px-5 rounded-lg shadow hover:bg-blue-700 transition"
          onClick={() => setShowModal(true)}
        >
          + 新增
        </button>
      </div>

      <p className="mb-6 text-gray-700 dark:text-gray-300">
        在这里你可以添加、修改、删除和部署 CDN 配置。
      </p>

      {/* 表格 */}
      <div className="relative overflow-x-auto rounded-lg shadow">
        <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
          <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
            <tr>
              <th scope="col" className="px-6 py-3">ID</th>
              <th scope="col" className="px-6 py-3">加速域名</th>
              <th scope="col" className="px-6 py-3">源站 IP</th>
              <th scope="col" className="px-6 py-3">CANME</th>
              <th scope="col" className="px-6 py-3 text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {records.map(record => (
              <tr
                key={record.id}
                className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 transition"
              >
                <td className="px-6 py-4">{record.id}</td>
                <td className="px-6 py-4">{record.domain}</td>
                <td className="px-6 py-4">{record.originIp}</td>
                {/* <td className="px-6 py-4">
                  {record.nodes && record.nodes.length > 0
                    ? record.nodes.map(node => node.name || node.host).join(", ")
                    : "未部署节点"}
                </td> */}
                <td className="px-6 py-4">
                  {record.cname
                    ? record.cname.domain
                    : "未部署节点"}
                </td>
                <td className="px-6 py-4 flex justify-end space-x-2">
                  <button
                    className={`py-1.5 px-3 rounded-lg transition ${record.ifDeploy ? 'bg-blue-300 text-gray-200 cursor-not-allowed' : 'bg-blue-500 text-white hover:bg-blue-600'}`}
                    onClick={() => !record.ifDeploy && handleEditRecord(record.id)}
                    disabled={record.ifDeploy}
                  >
                    编辑
                  </button>
                  <button
                    className={`py-1.5 px-3 rounded-lg transition ${record.ifDeploy ? 'bg-red-300 text-gray-200 cursor-not-allowed' : 'bg-red-500 text-white hover:bg-red-600'}`}
                    onClick={() => !record.ifDeploy && handleDeleteRecord(record.id)}
                    disabled={record.ifDeploy}
                  >
                    删除
                  </button>
                  {record.ifDeploy ? (
                    <button
                      className="bg-gray-500 text-white py-1.5 px-3 rounded-lg hover:bg-gray-600 transition"
                      onClick={() => {
                        if (window.confirm("确定要下线吗？")) {
                          handleOffline(record.id);
                        }
                      }}
                    >
                      下线
                    </button>
                  ) : (
                    <button
                      className="bg-green-500 text-white py-1.5 px-3 rounded-lg hover:bg-green-600 transition"
                      onClick={() => {
                        if (window.confirm("确定要部署吗？")) {
                          handleDeploy(record.id);
                        }
                      }}
                    >
                      部署
                    </button>
                  )}
                  {record.fullchain && record.privkey && (
                    <div className="relative">
                      <button
                        onClick={() => handleShowCert(record)}
                        className="bg-purple-500 text-white px-2 py-1 rounded hover:bg-purple-600"
                      >
                        查看证书
                      </button>
                      {/* 小提示 */}
                      {record.cert_apply_time && (
                        <span className="absolute -top-2 -right-4 bg-yellow-400 text-black text-xs px-1 rounded-full">
                          {Math.ceil(
                            (Date.now() - new Date(record.cert_apply_time.split('.')[0]).getTime()) /
                            (1000 * 60 * 60 * 24)
                          )}天前
                        </span>
                      )}
                    </div>
                  )}
                  {/* 清除缓存按钮 */}
                  <button
                    className="bg-yellow-500 text-white py-1.5 px-3 rounded-lg hover:bg-yellow-600 transition"
                    onClick={() => handleClearCache(record.id)}
                  >
                    清除缓存
                  </button>
                </td>
              </tr>
            ))}
            {records.length === 0 && (
              <tr>
                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">
                  暂无数据
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 弹窗 */}
      {showModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div
            className="absolute inset-0 bg-black bg-opacity-40"
            onClick={() => setShowModal(false)}
          ></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md max-h-[90vh] overflow-auto">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
              {currentRecordId !== null ? '编辑配置' : '新增配置'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label htmlFor="domain" className="block text-gray-700 dark:text-gray-300 mb-1">加速域名</label>
                <input
                  type="text"
                  id="domain"
                  value={domain}
                  onChange={(e) => setDomain(e.target.value)}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label htmlFor="originIp" className="block text-gray-700 dark:text-gray-300 mb-1">源站 IP</label>
                <input
                  type="text"
                  id="originIp"
                  value={originIp}
                  onChange={(e) => setOriginIp(e.target.value)}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 新增节点选择 */}
              {/* <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">选择节点</label>
                <div className="max-h-40 overflow-auto border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 p-2">
                  {nodes.map((node) => (
                    <label key={node.id} className="flex items-center space-x-2 mb-1">
                      <input
                        type="checkbox"
                        checked={selectedNodes.includes(node.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedNodes([...selectedNodes, node.id]);
                          } else {
                            setSelectedNodes(selectedNodes.filter((id) => id !== node.id));
                          }
                        }}
                        className="w-4 h-4"
                      />
                      <span className="text-gray-700 dark:text-gray-300">{node.name} ({node.host})</span>
                    </label>
                  ))}
                </div>
              </div> */}


              {/* 选择cname */}
  <div>
  <label className="block text-gray-700 dark:text-gray-300 mb-1">选择CNAME</label>
  <div className="max-h-40 overflow-auto border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 p-2 flex items-center justify-center">
    {cnames.length > 0 ? (
      <div className="w-full">
        {cnames.map((cname) => (
          <label key={cname.id} className="flex items-center space-x-2 mb-1">
            <input
              type="radio"
              name="selectedCNAME"
              value={cname.id}
              checked={selectedCNAME === cname.id}
              onChange={() => setSeleectCNAME(cname.id)}
              className="w-4 h-4"
            />
            <span className="text-gray-700 dark:text-gray-300">{cname.domain}</span>
          </label>
        ))}
      </div>
    ) : (
      <div className="text-center p-4 bg-gray-100 dark:bg-gray-800 rounded-md">
        <p className="text-gray-500 dark:text-gray-400 mb-2">暂无CNAME</p>
        <a
          href="/admin/cname"
          className="text-blue-500 dark:text-blue-400 underline font-medium"
        >
          前往CNAME配置中添加
        </a>
      </div>
    )}
  </div>
</div>


              <div className="flex justify-end space-x-3 pt-2">
                <button
                  type="button"
                  className="bg-gray-400 text-white py-2 px-4 rounded-lg hover:bg-gray-500 transition"
                  onClick={() => setShowModal(false)}
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition"
                >
                  {currentRecordId !== null ? '保存修改' : '添加配置'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}


      {/* 部署中模态框 */}
      {deployingId !== null && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="absolute inset-0 bg-black bg-opacity-40"></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-64 text-center">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">部署中…</h2>
            <p className="text-gray-700 dark:text-gray-300">请稍候，正在部署 CDN 配置</p>
            {/* 可加 loading 动画 */}
            <div className="mt-4">
              <div className="loader border-t-4 border-blue-500 rounded-full w-8 h-8 mx-auto animate-spin"></div>
            </div>
          </div>
        </div>
      )}

      {/* 下线中模态框 */}
      {offlineingId !== null && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="absolute inset-0 bg-black bg-opacity-40"></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-64 text-center">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">下线中…</h2>
            <p className="text-gray-700 dark:text-gray-300">请稍候，正在下线 CDN 配置</p>
            {/* 可加 loading 动画 */}
            <div className="mt-4">
              <div className="loader border-t-4 border-blue-500 rounded-full w-8 h-8 mx-auto animate-spin"></div>
            </div>
          </div>
        </div>
      )}

      {/* 清除缓存模态框 */}
      {clearCacheId !== null && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="absolute inset-0 bg-black bg-opacity-40"></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-64 text-center">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">清除缓存中...</h2>
            <p className="text-gray-700 dark:text-gray-300">请稍候，正在清除 CDN 缓存</p>
            {/* 可加 loading 动画 */}
            <div className="mt-4">
              <div className="loader border-t-4 border-blue-500 rounded-full w-8 h-8 mx-auto animate-spin"></div>
            </div>
          </div>
        </div>
      )}


      {/* 证书弹窗 */}
      {showCertModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="absolute inset-0 bg-black bg-opacity-40" onClick={() => setShowCertModal(false)}></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-2xl overflow-auto">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">证书内容</h2>
            <div className="mb-4">
              <label className="block mb-1 text-gray-700 dark:text-gray-300">fullchain.pem</label>
              <textarea
                readOnly
                value={selectedCert.fullchain}
                className="w-full h-40 p-2 border rounded bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
              />
              <button onClick={() => handleCopy(selectedCert.fullchain)} className="mt-1 bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">复制 fullchain</button>
            </div>
            <div className="mb-4">
              <label className="block mb-1 text-gray-700 dark:text-gray-300">privkey.pem</label>
              <textarea
                readOnly
                value={selectedCert.privkey}
                className="w-full h-40 p-2 border rounded bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
              />
              <button onClick={() => handleCopy(selectedCert.privkey)} className="mt-1 bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">复制 privkey</button>
            </div>
            <div className="flex justify-end">
              <button onClick={() => setShowCertModal(false)} className="bg-gray-400 text-white px-4 py-2 rounded hover:bg-gray-500">关闭</button>
            </div>
          </div>
        </div>
      )}

      {errorMsg && (
        <div className="fixed top-4 right-4 bg-red-500 text-white p-4 rounded-lg shadow-lg z-50 whitespace-pre-line">
          {errorMsg}
          <button
            onClick={() => setErrorMsg(null)}
            className="ml-4 bg-white text-red-500 px-2 py-1 rounded hover:bg-gray-100"
          >
            关闭
          </button>
        </div>
      )}

    </div>
  );
};

export default CdnConfigPage;
